package com.learn.window;

import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;

/**
 * @create: 2023-04-19 17:31
 * @author: Mr.Du
 * --------------
 * @notes: 不分组划分窗口，调用reduce对窗口内数据进行聚合
 **/
public class CountWindowAllReduceDemo {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource<String> streamSource = env.socketTextStream("node1", 9999);

        SingleOutputStreamOperator<Integer> nums = streamSource.map(Integer::parseInt);
        //划分window
        AllWindowedStream<Integer, GlobalWindow> windowedStream = nums.countWindowAll(5);

        //把窗口内数据进行聚合
        //windowedStream.sum(0).print();
        windowedStream.reduce(new ReduceFunction<Integer>() {
            @Override
            public Integer reduce(Integer v1, Integer v2) throws Exception {

                System.out.println("reduce中间计算结果：" + (v1+v2));
                return v1+v2;
            }
        }).print();
        env.execute();
    }
}
